//引入express模块
const express = require('express')
//引用数据库连接池
const pool = require('../pool.js')
//创建路由器
const slr = express.Router()

//页面地址 http://127.0.0.1:8080/shoppinglist.html

//请求方式 get
//路由地址  127.0.0.1:8080/shoppinglist/selectAll
//接收传参的方法 pool.query
slr.get('/selectAll',(req,res)=>{
    // console.log(req.query)
    pool.query('select * from good',(err,data)=>{
        if(err){
            next(err)
            return
        }
        // console.log(data)
        //判断是否查询到数据
        if(data.length == 0){
            res.send({
                "code":0,
                "msg":"没有找到"
            })
        }else{
            res.send({
                "code": 1,
                "msg": "找到商品信息",
                "data":data
            })
        }
    })
})

slr.get('/getgood',(req,res)=>{
     let obj = parseInt(req.query.gid)
     //console.log(parseInt(obj))
     
    let sql = `select * from good where gid=?`
    // console.log(gid)
    pool.query(sql,[obj],(err,data)=>{
        if(err){
            next(err)
            return
        }
        // console.log(data)
        //判断是否查询到数据
        if(data.length == 0){
            res.send({
                "code":0,
                "msg":"没有找到"
            })
        }else{
            res.send({
                "code": 1,
                "msg": "找到商品信息",
                "data":data
            })
        }
    })
})

slr.post('/changegood',(req,res,next)=>{
    // console.log(obj)
    let bid = parseInt(req.body.aid)
    let bname = req.body.aname
    let bprice = parseFloat(req.body.aprice)
    let bnum = parseInt(req.body.anum)
    let bsale = parseInt(req.body.asale)
    let sql = `update good set gname=?,gprice=?,gnum=?,gsale=? where gid=?`
    // console.log(gid)
    pool.query(sql,[bname,bprice,bnum,bsale,bid],(err,r)=>{
       if(err){
           next(err)
           return
       }
    //    console.log(data)
    //    判断是否修改到数据
       if(r.affectedRows==0){
           res.send({
               "code":0,
               "msg":"修改失败"
           })
       }else{
           res.send({
               "code": 1,
               "msg": "修改成功",
           })
       }
   })
})
module.exports = slr


